package java8.atguigu.teacher.datatime;

import org.junit.Test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @program lambda
 * @description:
 * @author: zhanglu
 * @create: 2019-06-02 14:40:00
 */
public class TestSimpleDateFormat {

    /*
        多线程，不安全
     */
    @Test
    public void test01() throws ExecutionException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Callable<Date> task = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return sdf.parse("20190602");
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> futures = new ArrayList<>();
        for(int i=0; i<10; i++){
            futures.add(pool.submit(task));
        }
        for(Future<Date> future : futures){
            System.out.println(future.get());
        }
    }

    /*
        多线程，不安全，修改报错问题
     */
    @Test
    public void test02() throws ExecutionException, InterruptedException {
        Callable<Date> task = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return conver("20190602");
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<Date>> futures = new ArrayList<>();
        for(int i=0; i<10; i++){
            futures.add(pool.submit(task));
        }
        for(Future<Date> future : futures){
            System.out.println(future.get());
        }

        pool.shutdown();
    }

    /*
        java8的多线程
     */
    @Test
    public void test03() throws ExecutionException, InterruptedException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        Callable<LocalDate> task = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20190602", dtf);
            }
        };
        ExecutorService pool = Executors.newFixedThreadPool(10);
        List<Future<LocalDate>> futures = new ArrayList<>();
        for(int i=0; i<10; i++){
            futures.add(pool.submit(task));
        }
        for(Future<LocalDate> future : futures){
            System.out.println(future.get());
        }

        pool.shutdown();
    }

    private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){
        protected DateFormat initialValue(){
            return new SimpleDateFormat("yyyyMMdd");
        }
    };

    public static Date conver(String source) throws Exception{
        return df.get().parse(source);
    }

}
